"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"

interface SettingsContextType {
  apiKey: string
  setApiKey: (key: string) => void
  clearApiKey: () => void
}

const SettingsContext = createContext<SettingsContextType | undefined>(undefined)

export function SettingsProvider({ children }: { children: ReactNode }) {
  const [apiKey, setApiKey] = useState<string>("")

  // 在组件挂载时从localStorage加载API密钥
  useEffect(() => {
    const storedApiKey = localStorage.getItem("openweather_api_key")
    if (storedApiKey) {
      setApiKey(storedApiKey)
    }
  }, [])

  // 保存API密钥到localStorage
  const saveApiKey = (key: string) => {
    setApiKey(key)
    localStorage.setItem("openweather_api_key", key)
  }

  // 清除API密钥
  const clearApiKey = () => {
    setApiKey("")
    localStorage.removeItem("openweather_api_key")
  }

  return (
    <SettingsContext.Provider
      value={{
        apiKey,
        setApiKey: saveApiKey,
        clearApiKey,
      }}
    >
      {children}
    </SettingsContext.Provider>
  )
}

export function useSettings() {
  const context = useContext(SettingsContext)
  if (context === undefined) {
    throw new Error("useSettings must be used within a SettingsProvider")
  }
  return context
}
